<template>
  <div>
    <!-- Hero Section -->
    <div class="relative">
      <div class="banner-container">
        <!-- 轮播图容器 -->
        <div class="carousel-wrapper" ref="carouselContainer">
          <!-- 轮播内容容器 -->
          <div class="carousel-track" ref="carouselTrack">
            <!-- 实际的轮播slides -->
            <div v-for="(slide, index) in slides" :key="index"
                 class="carousel-slide"
                 :class="{ active: currentSlide === index }"
                 @click="handleSlideClick(slide)"
                 style="cursor: pointer;">
              <!-- 左右布局容器 -->
              <div class="slide-content">
                <!-- 左侧文字部分 - 40% -->
                <div class="text-section">
                  <!-- 上部分内容 -->
                  <div class="text-content">
                    <!-- subtitle -->
                    <p class="subtitle">WELCOME TO CBAM Service Platform</p>
                    <!-- title -->
                    <h1 class="title">{{ slide.title }}</h1>
                    <!-- 按钮 - 隐藏 -->
                    <!-- <button @click="handleSlideClick(slide)" class="cta-button">
                      {{ slide.buttonText }}
                    </button> -->
                  </div>
                </div>

                <!-- 右侧图片部分 - 60% -->
                <div class="image-section">
                  <div class="image-container">
                    <img :src="slide.image" alt="" class="slide-image" />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 底部轮播序号 - 移到外层，不参与淡入淡出 -->
          <div class="slide-indicators-fixed">
            <span
              v-for="(_, slideIndex) in slides"
              :key="slideIndex"
              class="indicator"
              :class="{ active: currentSlide === slideIndex }"
              @click.stop="goToSlide(slideIndex)">
              {{ String(slideIndex + 1).padStart(2, '0') }}
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="hezi bg-white rounded-lg  cursor-pointer duration-300 max-w-7xl mx-auto  " style="padding-top: 80px;">
      <div class="flex h-full">
        <!-- Left side content -->
        <div class="flex-1 p-6" style="padding-right: 200px;">
          <div class="mb-3">
            <span class="text-blue-600 text-sm font-medium paragraph-subhealing">— Carbon tariff calculator</span>
          </div>

          <h2 class="text-2xl font-bold text-gray-900 mb-3 paragraph-healing">
            CBAM<br>
            Accounting Services
          </h2>

          <p class="text-gray-600 text-xs mb-4 leading-relaxed" style="font-size: 16px;line-height: 28px;color: #828282;">
            We provide a comprehensive Carbon Border Adjustment Mechanism (CBAM) compliance solution to help businesses
            tackle the challenges of EU carbon tariffs.
          </p>

          <!-- Progress bar -->
          <div class="mb-0 mt-1" style="width:50%;">
            <div class="flex items-center justify-between mb-2">
              <span class="text-xs text-gray-700">save</span>
              <span class="text-xs font-medium text-gray-900">80%</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-1.5">
              <div class=" h-1.5 rounded-full" style="width: 80%;background-color: #4887c5;"></div>
            </div>
          </div>
        </div>

        <!-- Right side content -->
        <div class=" p-6 rounded-lg flex flex-col justify-center w-128" style="background-color: #edf3f9;"
        @click="navigateTo('/echart/listIndustry')">
          <h2 class="text-lg font-bold text-gray-900 mb-1" style="line-height: 44px;color: #1F2220;font-size: 32px;">Save costs</h2>
          <h2 class="text-lg font-bold text-gray-900 mb-5" style="line-height: 44px;color: #1F2220;font-size: 32px;">Green transtion</h2>
          <p class="text-xxxs text-gray-500 mb-10" style="font-weight: 400;font-size: 16px;color: #828282;line-height: 28px;">
         <br>
         Reduce carbon risk and cost, pursuing green and high-quality growth when moving for a sustainable future
          </p>
          <div>
            <button style="background-color: #2b649c;width: 100%;padding-left:15px;"
              class="cursor-pointer hover:bg-blue-700 text-white px-4 py-4 rounded-lg font-medium transition-all duration-300 transform hover:scale-105 flex items-center justify-between text-lg">
              <span>Start Calculating</span>
              <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"></path>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="chengshi relative"
      style="background-image: url('../images/bgchengshi.png'); background-size: 100% 50%; background-repeat: no-repeat; background-position: bottom; min-height: 400px; padding: 80px 0;">
      <div class="max-w-7xl mx-auto px-0">
        <div class="grid grid-cols-1 md:grid-cols-5 items-stretch divide-x divide-gray-300">

          <!-- Corporate Carbon Accounting -->
          <div class="text-center cursor-pointer px-4 h-48 flex flex-col justify-between relative"
            @click="navigateTo('/plan/qiye')">
            <div
              class="group transition-all duration-300 transform hover:scale-105 hover:drop-shadow-lg h-full flex flex-col justify-between">
              <div class="flex flex-col items-center">
                <div
                  class="w-16 h-16 mx-auto mb-4 bg-white rounded-lg shadow-md flex items-center justify-center group-hover:shadow-lg transition-shadow">
                  <img src="/images/deng.png" alt="Corporate Carbon Accounting" class="w-8 h-8">
                </div>
                <h3 class="text-lg font-bold text-gray-900 mb-2">Carbon Calculator V2.0</h3>
              </div>
              <p class="text-sm text-gray-600 leading-relaxed">
                Ambition Enterprise Carbon Calculator v2.0
              </p>
            </div>
          </div>

          <!-- Catering Carbon Accounting -->
          <div class="text-center cursor-pointer px-4 h-48 flex flex-col justify-between relative"
            @click="navigateTo('/plan/can')">
            <div
              class="group transition-all duration-300 transform hover:scale-105 hover:drop-shadow-lg h-full flex flex-col justify-between">
              <div class="flex flex-col items-center">
                <div
                  class="w-16 h-16 mx-auto mb-4 bg-white rounded-lg shadow-md flex items-center justify-center group-hover:shadow-lg transition-shadow">
                  <img src="/images/feng2.png" alt="Catering Carbon Accounting" class="w-8 h-8">
                </div>
                <h3 class="text-lg font-bold text-gray-900 mb-2">Catering Carbon Accounting</h3>
              </div>
              <p class="text-sm text-gray-600 leading-relaxed">
                Catering Emission Accounting Platform
              </p>
            </div>
          </div>
          
          <!-- Corporate Social Responsibility -->
          <div class="text-center cursor-pointer px-4 h-48 flex flex-col justify-between relative"
            @click="navigateTo('/plan/CSR')">
            <div
              class="group transition-all duration-300 transform hover:scale-105 hover:drop-shadow-lg h-full flex flex-col justify-between">
              <div class="flex flex-col items-center">
                <div
                  class="w-16 h-16 mx-auto mb-4 bg-white rounded-lg shadow-md flex items-center justify-center group-hover:shadow-lg transition-shadow">
                  <img src="/images/gong.png" alt="Corporate Social Responsibility" class="w-8 h-8">
                </div>
                <h3 class="text-lg font-bold text-gray-900 mb-2">Corporate Social Responsibility</h3>
              </div>
              <p class="text-sm text-gray-600 leading-relaxed">
                (CSR) is a self-regulating business model that helps companies ...
              </p>
            </div>
            </div>
            
          <!-- CE3METL model -->
          <div class="text-center cursor-pointer px-4 h-48 flex flex-col justify-between relative"
            @click="navigateTo('/plan/foot')">
            <div
              class="group transition-all duration-300 transform hover:scale-105 hover:drop-shadow-lg h-full flex flex-col justify-between">
              <div class="flex flex-col items-center">
                <div
                  class="w-16 h-16 mx-auto mb-4 bg-white rounded-lg shadow-md flex items-center justify-center group-hover:shadow-lg transition-shadow">
                  <img src="/images/wu.png" alt="CE3METL Model" class="w-8 h-8">
                </div>
                <h3 class="text-lg font-bold text-gray-900 mb-2">CARBON OFFSET</h3>
              </div>
              <p class="text-sm text-gray-600 leading-relaxed">
                Carbon offsetting, also known as carbon compensation, is a way...
              </p>
            </div>
          </div>

          <!-- ESG Management -->
          <div class="text-center cursor-pointer px-4 h-48 flex flex-col justify-between relative"
            @click="navigateTo('/plan/ESG')">
            <div
              class="group transition-all duration-300 transform hover:scale-105 hover:drop-shadow-lg h-full flex flex-col justify-between">
              <div class="flex flex-col items-center">
                <div
                  class="w-16 h-16 mx-auto mb-4 bg-white rounded-lg shadow-md flex items-center justify-center group-hover:shadow-lg transition-shadow">
                  <img src="/images/ye.png" alt="ESG Management" class="w-8 h-8">
                </div>
                <h3 class="text-lg font-bold text-gray-900 mb-2">ESG Management</h3>
              </div>
              <p class="text-sm text-gray-600 leading-relaxed">
                Environmental, Social and Governance (ESG) is a ...
              </p>
            </div>
          </div>

        </div>
      </div>
    </div>

    <div class="content " style="background: linear-gradient( 180deg, #EDF3F9 0%, #FFFFFF 100%);padding-top: 80px;">
      <div class="max-w-7xl mx-auto px-4 ">
        <!-- Carbon Neutrality Pathway Section -->
        <section class="mb-16">
          <div class="flex items-center justify-between mb-8">
            <div>
              <p class="text-sm font-medium mb-2 paragraph-subhealing" style="color: #2b649c;">RESEARCH UPDATES</p>
              <h2 class="text-3xl font-bold text-gray-900 paragraph-healing">Publications and Achievements</h2>
            </div>
            <!-- <NuxtLink to="/member/dynamics"> <button
                class="text-white cursor-pointer px-6 py-2 rounded-lg font-medium transition-colors"
                style="background-color: #2b649c;" onmouseover="this.style.backgroundColor='#1e4a73'"
                onmouseout="this.style.backgroundColor='#2b649c'">
                READ MORE >
              </button> </NuxtLink> -->

          </div>

          <!-- Publications and Achievements 轮播容器 -->
          <div class="relative" style="padding: 2rem 2rem 4rem 2rem;">
            <!-- 左箭头按钮 -->
            <button
              v-if="canShowPublicationsCarouselButtons"
              @click="publicationsScrollPrev"
              :disabled="!canPublicationsScrollPrev"
              class="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-16 z-10
                     w-12 h-12 rounded-full border-2 flex items-center justify-center
                     transition-all duration-300
                     disabled:opacity-30 disabled:cursor-not-allowed"
              :class="canPublicationsScrollPrev 
                ? 'bg-[#2B649C] border-[#2B649C] hover:bg-[#1e4870] cursor-pointer' 
                : 'bg-gray-300 border-gray-300'"
            >
              <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
              </svg>
            </button>

            <!-- 卡片容器 -->
            <div class="overflow-hidden" style="margin: -2rem -2rem -4rem -2rem; padding: 2rem 2rem 4rem 2rem;"
                 @mouseenter="stopPublicationsAutoPlay"
                 @mouseleave="startPublicationsAutoPlay">
              <div 
                class="flex transition-transform duration-500 ease-in-out"
                :style="{ transform: publicationsTransformOffset }"
                style="gap: 3rem;"
              >
                <div 
                  v-for="(item, index) in carbonPathList" 
                  :key="item.id"
                  class="flex-shrink-0"
                  style="width: calc((100% - 6rem) / 3);"
                >
                  <div 
                    class="content-grid-item rounded-lg overflow-hidden shadow-lg cursor-pointer
                           hover:shadow-[0px_20px_60px_0px_rgba(0,82,160,0.3)] transition-all duration-300 transform hover:scale-105"
                    style="height: 380px;"
                    @click="navigateTo(`/article/${item.id}`)"
                  >
                    <div class="h-56 bg-gray-200 flex items-center justify-center">
                      <img v-if="item.profileUrl" :src="item.profileUrl" :alt="item.title" class="w-full h-full object-cover">
                      <div v-else :class="getGradientClass(index % 3)" class="w-full h-full"></div>
                    </div>
                    <div class="p-6 flex flex-col justify-between" style="height: calc(380px - 14rem);">
                      <h3 class="text-lg font-bold text-gray-900 mb-3 leading-tight line-clamp-3">
                        {{ item.title || 'Carbon Neutrality Research Article' }}
                      </h3>
                      <!-- <p class="text-sm text-gray-600 mb-4 line-clamp-3 content-detailed" v-html="item.detailed"></p> -->
                      <p class="text-sm font-medium" style="color: #2b649c;">{{ formatDate(new Date()) }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 右箭头按钮 -->
            <button
              v-if="canShowPublicationsCarouselButtons"
              @click="publicationsScrollNext"
              :disabled="!canPublicationsScrollNext"
              class="absolute right-0 top-1/2 -translate-y-1/2 translate-x-16 z-10
                     w-12 h-12 rounded-full border-2 flex items-center justify-center
                     transition-all duration-300
                     disabled:opacity-30 disabled:cursor-not-allowed"
              :class="canPublicationsScrollNext 
                ? 'bg-[#2B649C] border-[#2B649C] hover:bg-[#1e4870] cursor-pointer' 
                : 'bg-gray-300 border-gray-300'"
            >
              <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
              </svg>
            </button>
          </div>
        </section>


        <!-- Selected models Section -->

      </div>

    </div>

    <!--  -->

    <div style="position: relative;margin-top: 150px;">
      <div class="p-15"  style="background-color:#edf3f9; height: 300px;position: absolute;right: 0;top: 0;width: 55vw;">
        <img src="/images/FeaturedNews.png" alt="" style="width: 70%;height: 80px;">
      </div>
      <div class="ffff flex gap-10 mb-16 mx-auto max-w-7xl" >
      <div class="left w-1/3">
        <div class="mb-8 flex items-center justify-between" style="margin-bottom: 42px;">
          <div>
            <p class="text-sm font-medium mb-2 paragraph-subhealing" style="color: #2b649c;">BROWSE THE LATEST</p>
            <h2 class="text-3xl font-bold text-gray-900 paragraph-healing">Featured News</h2>
          </div>
        </div>

                 <!-- 文章图片 -->
         <div class="mb-6">
           <img v-if="featuredNewsList[0]?.profileUrl" :src="featuredNewsList[0].profileUrl" :alt="featuredNewsList[0].title" class="w-full h-64 object-cover rounded-lg">
           <div v-else class="w-full h-64 bg-gradient-to-br from-blue-400 to-blue-600 rounded-lg"></div>
         </div>

                 <!-- 三个新闻项 -->
         <div class="space-y-4">
           <div v-for="(item, index) in featuredNewsList.slice(0, 3)" :key="item.id"
             class="pb-4 border-b border-gray-200 cursor-pointer hover:bg-gray-50  hover:text-[#2B649C] transition-colors"
             @click="navigateTo(`/article/${item.id}`)">
             <h3 class="font-bold text-gray-900 mb-2 text-base leading-tight line-clamp-2  hover:text-[#2B649C]">
               {{ item.title || getNewsTitle(index) }}
             </h3>
           </div>
         </div>

      </div>

      <div class="right flex-1" style="margin-top: 60px;">
        <!-- 折叠卡片容器 -->
        <div class="relative">
                     <!-- 主卡片 -->
                      <div class="relative" style="height: 500px;margin-top: 100px;"
                           @mouseenter="stopNewsAutoPlay"
                           @mouseleave="startNewsAutoPlay">
              <div v-for="(item, index) in featuredNewsList.slice(3, 6)" :key="item.id"
                class="absolute bg-white rounded-lg overflow-hidden shadow-lg cursor-pointer transition-all duration-500"
                :class="index === newsCurrentSlide ? 'z-30' : index === (newsCurrentSlide + 1) % 3 ? 'z-20' : 'z-10'"
                :style="getCardStyle(index)" @click="navigateTo(`/article/${item.id}`)">
               <div class="relative" style="height: 480px;">
                <img v-if="item.profileUrl" :src="item.profileUrl" :alt="item.title" class="w-full h-full object-cover">
                <div v-else class="w-full h-full bg-gradient-to-br from-blue-400 to-blue-600"></div>

                <!-- 卡片上的文字叠加 -->
                <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-6">
                  <div class="text-white text-xs mb-2">{{ formatDate(new Date()) }}</div>
                  <h3 class="text-white font-bold text-lg leading-tight line-clamp-2">
                    {{ item.title || `News Article ${index + 1}` }}
                  </h3>
                  <!-- <p class="text-white/80 text-sm mt-2 line-clamp-2">
                    Latest research and developments in carbon neutrality and environmental economics from our academic
                    team.
                  </p> -->
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 翻页按钮 -->
        <div class="flex items-center justify-between mt-6">
          <div class="flex items-center space-x-4">
            <button @click="newsPreviousSlide"
              class="w-10 h-10 rounded-full border flex items-center justify-center transition-colors cursor-pointer"
              style="background-color: #2b649c; border-color: #2b649c;">
              <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
              </svg>
            </button>
            <button @click="newsNextSlide"
              class="w-10 h-10 rounded-full border flex items-center justify-center transition-colors cursor-pointer"
              style="background-color: #2b649c; border-color: #2b649c;">
              <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
              </svg>
            </button>
          </div>

          <!-- <button class="text-white cursor-pointer px-6 py-2 rounded-lg font-medium transition-colors"
            style="background-color: #2b649c;" @click="navigateTo('/member/dynamics')">
            READ MORE >
          </button> -->
        </div>
      </div>
    </div>
    </div>
    <div style="background-color: #fff;margin-top: 20px;">
      <div style="height: 20px;"></div>
      <img src="/images/CBAM Service@2x.png" alt="" style="width: 70vw;margin-top: 50px;" class="mx-auto">
      <section class="mb-16 max-w-7xl mx-auto p-20 selected-section" style="background-color:#edf3f9 ;border-radius: 20px;">
        <div class="mb-8 flex items-center justify-between">
          <div>
            <p class="text-sm font-medium mb-2 paragraph-subhealing" style="color: #2b649c;">Model Communities</p>
            <h2 class="text-3xl font-bold text-gray-900 paragraph-healing">Selected Models</h2>
          </div>
          <div style="width: 40vw;font-size: 12px;color: #999;">
            Our Selected Models include a comprehensive set of independently developed Integrated Assessment Models (IAMs) covering global, regional, and national scales, as well as other models designed to assess climate impacts.
          </div>
        </div>

        <!-- Top banner image -->
        <!-- <div class="mb-8">
            <img src="../images/CBAM Service@2x.png" alt="CBAM Service" class="w-full h-auto rounded-lg">
            <div class="bg-gray-50 p-6 rounded-b-lg">
              <p class="text-gray-600 text-sm leading-relaxed">
              </p>
            </div>
          </div> -->

        <!-- Three model cards with carousel -->
          <div class="relative" style="padding: 2rem 2rem 4rem 2rem;">
            <!-- 左箭头按钮 -->
            <!-- <button
              v-if="canShowCarouselButtons"
              @click="scrollPrev"
              :disabled="!canScrollPrev"
              class="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-16 z-10
                     w-12 h-12 rounded-full border-2 flex items-center justify-center
                     transition-all duration-300
                     disabled:opacity-30 disabled:cursor-not-allowed"
              :class="canScrollPrev 
                ? 'bg-[#2B649C] border-[#2B649C] hover:bg-[#1e4870] cursor-pointer' 
                : 'bg-gray-300 border-gray-300'"
            >
              <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
              </svg>
            </button> -->

            <!-- 卡片容器 -->
            <div class="overflow-hidden" ref="carouselContainer" style="margin: -2rem -2rem -4rem -2rem; padding: 2rem 2rem 4rem 2rem;"
                 @mouseenter="stopAutoPlay"
                 @mouseleave="startAutoPlay">
              <div 
                class="flex transition-transform duration-500 ease-in-out"
                :style="{ transform: transformOffset }"
                style="gap: 3rem;"
              >
                <NuxtLink 
                  v-for="card in modelCards" 
                  :key="card.id"
                  :to="card.linkUrl" 
                  class="flex-shrink-0 card-item"
                  style="width: calc((100% - 6rem) / 3);"
                >
                  <div 
                    class="bg-gray-50 p-6 rounded-lg border-2 border-white
                           hover:shadow-[0px_20px_60px_0px_rgba(0,82,160,0.3)]
                           hover:rounded-[10px]
                           hover:border-2
                           hover:border-[#2B649C] transition-all duration-300 transform hover:scale-105 hover:z-10"
                    style="height: 350px; position: relative;"
                  >
                    <h3 class="text-xl font-bold text-gray-900 mb-4">{{ card.title }}</h3>
                    <p class="text-gray-600 text-sm mb-6 leading-relaxed line-clamp-4">
                      {{ card.content }}
                    </p>
                    <div 
                      class="flex justify-center"
                      style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); width: 192px;"
                    >
                      <img 
                        :src="card.coverImage" 
                        :alt="card.title" 
                        class="w-48 h-32 object-contain"
                      />
                    </div>
                  </div>
                </NuxtLink>
              </div>
            </div>

            <!-- 右箭头按钮 -->
            <!-- <button
              v-if="canShowCarouselButtons"
              @click="scrollNext"
              :disabled="!canScrollNext"
              class="absolute right-0 top-1/2 -translate-y-1/2 translate-x-16 z-10
                     w-12 h-12 rounded-full border-2 flex items-center justify-center
                     transition-all duration-300
                     disabled:opacity-30 disabled:cursor-not-allowed"
              :class="canScrollNext 
                ? 'bg-[#2B649C] border-[#2B649C] hover:bg-[#1e4870] cursor-pointer' 
                : 'bg-gray-300 border-gray-300'"
            >
              <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
              </svg>
            </button> -->
          </div>
        </section>
      </div>

  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { articleApi, bannerApi } from '~/public/utils/api'

const currentSlide = ref(0)
const slides = ref([])
const selectedModels = ref([])
const carbonPathList = ref([])

// Publications and Achievements 轮播状态
const publicationsCurrentIndex = ref(0)
const PUBLICATIONS_PER_PAGE = 3  // 每页显示3个

// 计算属性：是否显示 Publications 轮播按钮
const canShowPublicationsCarouselButtons = computed(() => {
  return carbonPathList.value.length > PUBLICATIONS_PER_PAGE
})

// 计算属性：是否可以向前滚动
const canPublicationsScrollPrev = computed(() => publicationsCurrentIndex.value > 0)

// 计算属性：是否可以向后滚动
const canPublicationsScrollNext = computed(() => {
  return publicationsCurrentIndex.value + PUBLICATIONS_PER_PAGE < carbonPathList.value.length
})

// 计算属性：transform 偏移量
const publicationsTransformOffset = computed(() => {
  const offsetPercent = publicationsCurrentIndex.value * (100 / PUBLICATIONS_PER_PAGE)
  const offsetRem = publicationsCurrentIndex.value * 1
  return `translateX(calc(-${offsetPercent}% - ${offsetRem}rem))`
})

// Three Model Cards 数据
const modelCards = ref([])

// 轮播状态
const currentIndex = ref(0)
const CARDS_PER_PAGE = 3  // 每页显示3个卡片

// 计算属性：是否显示轮播按钮
const canShowCarouselButtons = computed(() => {
  return modelCards.value.length > CARDS_PER_PAGE
})

// 计算属性：是否可以向前滚动
const canScrollPrev = computed(() => currentIndex.value > 0)

// 计算属性：是否可以向后滚动
const canScrollNext = computed(() => {
  return currentIndex.value + CARDS_PER_PAGE < modelCards.value.length
})

// 计算属性：transform 偏移量
const transformOffset = computed(() => {
  // ⚠️ 修复：正确计算偏移量
  // 每个卡片实际宽度 = (100% - 6rem) / 3
  // 移动1个位置的距离 = 1个卡片 + 1个gap = (100% - 6rem) / 3 + 3rem = (100% + 3rem) / 3
  // 所以移动 n 个位置 = n * (100% + 3rem) / 3 = n * 100% / 3 + n * 1rem
  
  // 直接基于 currentIndex 计算偏移量（支持非整页的情况）
  const offsetPercent = currentIndex.value * (100 / CARDS_PER_PAGE)  // n * 33.333%
  const offsetRem = currentIndex.value * 1  // n * 1rem
  
  return `translateX(calc(-${offsetPercent}% - ${offsetRem}rem))`
})

// 默认 Model Cards（作为fallback）
const defaultModelCards = [
  {
    id: 1,
    title: 'CE3METL Model',
    content: 'CE3METL (Chinese Energy-Economy-Environmental Model with Endogenous Technological Change by Employing Logistic Curves) It is a global comprehensive assessment...',
    coverImage: '/images/CE3METL Model@2x.png',
    linkUrl: '/plan/CE3'
  },
  {
    id: 2,
    title: 'E3METL Model',
    content: 'E3METL (Economy-Energy-Environmental Model with Endogenous Technological Change by employing Logistic curves) The model is based on endogenous factors...',
    coverImage: '/images/E3METL model@2x.png',
    linkUrl: '/plan/E3M'
  },
  {
    id: 3,
    title: 'REEC Model',
    content: 'REEC (Regional Energy-Economy-Climate Model) The regional comprehensive assessment model for energy-economy-climate interactions...',
    coverImage: '/images/E3METL model@2x(1).png',
    linkUrl: '/plan/REEC'
  },
  {
    id: 4,
    title: 'CBAM Service Model',
    content: 'CBAM (Carbon Border Adjustment Mechanism) Service Model provides comprehensive carbon emission calculation and management solutions for enterprises facing carbon border tax regulations.',
    coverImage: '/images/CBAM Service@2x.png',
    linkUrl: '/solutions'
  }
]

// 新闻卡片轮播相关
const newsCurrentSlide = ref(0)

// 获取卡片样式（折叠效果）
const getCardStyle = (index) => {
  const current = newsCurrentSlide.value
  const total = 3

  if (index === current) {
    // 当前卡片：最前面，完全显示
    return {
      transform: 'translateX(0px) translateY(0px) scale(1)',
      opacity: 1,
      width: '100%'
    }
  } else if (index === (current + 1) % total) {
    // 下一张卡片：稍微向右向下偏移，稍小
    return {
      transform: 'translateX(20px) translateY(10px) scale(0.95)',
      opacity: 0.8,
      width: '100%'
    }
  } else {
    // 第三张卡片：更多偏移，更小
    return {
      transform: 'translateX(40px) translateY(20px) scale(0.9)',
      opacity: 0.6,
      width: '100%'
    }
  }
}

// 新闻上一页
const newsPreviousSlide = () => {
  const total = Math.min(3, featuredNewsList.value.slice(3, 6).length)
  newsCurrentSlide.value = newsCurrentSlide.value === 0 ? total - 1 : newsCurrentSlide.value - 1
}

// 新闻下一页
const newsNextSlide = () => {
  const total = Math.min(3, featuredNewsList.value.slice(3, 6).length)
  newsCurrentSlide.value = (newsCurrentSlide.value + 1) % total
}

// 从HTML中提取纯文本
const stripHtmlTags = (html) => {
  if (!html) return ''
  // 创建临时div元素来解析HTML
  if (process.client) {
    const tmp = document.createElement('div')
    tmp.innerHTML = html
    return tmp.textContent || tmp.innerText || ''
  }
  // 服务端渲染时使用简单的正则替换
  return html.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim()
}

// 滚动到下一页（每次滚动1个，用于自动轮播）
const scrollNext = () => {
  if (modelCards.value.length <= CARDS_PER_PAGE) return
  
  // 循环滚动：如果到达最后，回到第一个
  if (currentIndex.value >= modelCards.value.length - CARDS_PER_PAGE) {
    currentIndex.value = 0
  } else {
    currentIndex.value += 1
  }
}

// 滚动到上一页（每次滚动3个）
const scrollPrev = () => {
  if (canScrollPrev.value) {
    const prevIndex = currentIndex.value - CARDS_PER_PAGE
    currentIndex.value = Math.max(prevIndex, 0)
  }
}

// 自动轮播定时器
let autoPlayTimer = null
let publicationsAutoPlayTimer = null
let newsAutoPlayTimer = null

// 开始自动轮播
const startAutoPlay = () => {
  stopAutoPlay() // 先清除已有的定时器
  autoPlayTimer = setInterval(() => {
    scrollNext()
  }, 3000) // 每3秒滚动一次
}

// 停止自动轮播
const stopAutoPlay = () => {
  if (autoPlayTimer) {
    clearInterval(autoPlayTimer)
    autoPlayTimer = null
  }
}

// Publications 自动滚动到下一页
const publicationsScrollNextAuto = () => {
  if (carbonPathList.value.length <= PUBLICATIONS_PER_PAGE) return
  
  // 循环滚动：如果到达最后，回到第一个
  if (publicationsCurrentIndex.value >= carbonPathList.value.length - PUBLICATIONS_PER_PAGE) {
    publicationsCurrentIndex.value = 0
  } else {
    publicationsCurrentIndex.value += 1
  }
}

// 开始 Publications 自动轮播
const startPublicationsAutoPlay = () => {
  stopPublicationsAutoPlay()
  publicationsAutoPlayTimer = setInterval(() => {
    publicationsScrollNextAuto()
  }, 3000)
}

// 停止 Publications 自动轮播
const stopPublicationsAutoPlay = () => {
  if (publicationsAutoPlayTimer) {
    clearInterval(publicationsAutoPlayTimer)
    publicationsAutoPlayTimer = null
  }
}

// 开始 News 自动轮播
const startNewsAutoPlay = () => {
  stopNewsAutoPlay()
  newsAutoPlayTimer = setInterval(() => {
    newsNextSlide()
  }, 3000)
}

// 停止 News 自动轮播
const stopNewsAutoPlay = () => {
  if (newsAutoPlayTimer) {
    clearInterval(newsAutoPlayTimer)
    newsAutoPlayTimer = null
  }
}

// Publications 向后滚动
const publicationsScrollNext = () => {
  if (canPublicationsScrollNext.value) {
    const nextIndex = publicationsCurrentIndex.value + PUBLICATIONS_PER_PAGE
    publicationsCurrentIndex.value = Math.min(
      nextIndex,
      carbonPathList.value.length - PUBLICATIONS_PER_PAGE
    )
  }
}

// Publications 向前滚动
const publicationsScrollPrev = () => {
  if (canPublicationsScrollPrev.value) {
    const prevIndex = publicationsCurrentIndex.value - PUBLICATIONS_PER_PAGE
    publicationsCurrentIndex.value = Math.max(prevIndex, 0)
  }
}

// 获取 Three Model Cards 数据
const fetchModelCards = async () => {
  try {
    const result = await articleApi.getList({
      pageSize: 10,  // 多取一些，以防有些数据不符合要求
      pageNum: 1,
      categoryId: 8
    })
    
    const rows = result?.rows || []
    
    if (rows && rows.length > 0) {
      // 处理数据
      modelCards.value = rows.slice(0, 10).map(item => ({
        id: item.id,
        title: item.title || '',
        content: stripHtmlTags(item.detailed || ''),  // 只提取纯文本，不截断
        coverImage: item.profileUrl || '',
        linkUrl: `/article/${item.id}`
      }))
    }
  } catch (error) {
    console.error('Failed to fetch model cards:', error)
    // 接口调用失败，使用默认卡片
    modelCards.value = defaultModelCards
  }
}

// 获取banner数据
const fetchBannerData = async () => {
    const result = await bannerApi.getList()
    const list = Array.isArray(result?.data) ? result.data : (Array.isArray(result?.rows) ? result.rows : null)
    if (list) {
      slides.value = list.map(item => ({
        image: item.pictureUrl,
        title: item.title,
        subtitle: item.subtitle || item.subTitle || 'FEATURED CONTENT',
        buttonText: item.buttonText || 'Learn More',
        linkUrl: item.linkUrl || item.href || ''
      }))
    }
}



const goToSlide = (index) => {
  currentSlide.value = index
}



let autoSlideInterval

const handleSlideClick = (slide) => {
  if (!slide || !slide.linkUrl) return
  if (/^https?:\/\//i.test(slide.linkUrl)) {
    window.open(slide.linkUrl, '_blank')
  } else {
    navigateTo(slide.linkUrl)
  }
}

onMounted(async () => {
  // 获取banner数据
  await fetchBannerData()
  // 获取 Three Model Cards 数据
  await fetchModelCards()
  // 获取 Selected models 数据
  await fetchSelectedModels()
  await fetchCarbonPath()
  // 获取 Featured News 数据
  await fetchFeaturedNews()

  // 自动轮播，每5秒切换一次
  autoSlideInterval = setInterval(() => {
    const len = slides.value.length || 1
    currentSlide.value = (currentSlide.value + 1) % len
  }, 5000)
  
  // 启动Model Cards自动轮播
  startAutoPlay()
  // 启动Publications自动轮播
  startPublicationsAutoPlay()
  // 启动News自动轮播
  startNewsAutoPlay()
})

onUnmounted(() => {
  if (autoSlideInterval) {
    clearInterval(autoSlideInterval)
  }
  stopAutoPlay()
  stopPublicationsAutoPlay()
  stopNewsAutoPlay()
})

// 设置页面标题
useHead({
  title: 'Home - Carbon Tariff Platform',
  meta: [
    { name: 'description', content: 'Carbon Border Adjustment Mechanism (CBAM) service platform providing comprehensive carbon tariff solutions for global enterprises' },
    { name: 'keywords', content: 'carbon tariff platform, CBAM service, carbon accounting, carbon neutrality pathway' }
  ]
})

// 选型模型数据
async function fetchSelectedModels() {
  try {
    const res = await articleApi.getList({ pageSize: 3, pageNum: 1, categoryId: 1 })
    const rows = res?.rows || res?.data?.rows || []
    selectedModels.value = rows.map(r => ({
      id: r.id || r.articleId,
      title: r.title || '',
      summary: r.summary || (typeof r.content === 'string' ? r.content.replace(/<[^>]+>/g, '').slice(0, 120) : '')
    }))
  } catch (e) {
    selectedModels.value = []
  }
}

// Carbon Neutrality Pathway 数据
async function fetchCarbonPath() {
  try {
    const res = await articleApi.getList({ pageSize: 10, pageNum: 1, categoryId: 3 })
    const rows = res?.rows || res?.data?.rows || []
    carbonPathList.value = rows.map(r => ({
      id: r.id || r.articleId,
      title: r.title || '',
      profileUrl: r.profileUrl || r.pictureUrl || r.image || '',
      detailed: removeStyleAttributes(r.detailed || '')
    }))
  } catch (e) {
    carbonPathList.value = []
  }
}

// Featured News 数据
const featuredNewsList = ref([])

async function fetchFeaturedNews() {
  try {
    const res = await articleApi.getList({ pageSize: 10, pageNum: 1, categoryId: 7 })
    const rows = res?.rows || res?.data?.rows || []
    featuredNewsList.value = rows.map(r => ({
      id: r.id || r.articleId,
      title: r.title || '',
      profileUrl: r.profileUrl || r.pictureUrl || r.image || ''
    }))
  } catch (e) {
    featuredNewsList.value = []
  }
}

// 去掉HTML中的style属性
function removeStyleAttributes(htmlString) {
  if (!htmlString) return ''
  // 使用正则表达式去掉所有的style属性
  return htmlString.replace(/\s*style\s*=\s*["'][^"']*["']/gi, '')
}

// 获取渐变样式类
function getGradientClass(index) {
  const gradients = [
    'bg-gradient-to-br from-orange-400 to-pink-400',
    'bg-gradient-to-br from-yellow-400 to-orange-500',
    'bg-gradient-to-br from-blue-500 to-green-400'
  ]
  return gradients[index % gradients.length]
}

// 格式化日期
function formatDate(date) {
  return date.toLocaleDateString('en-GB', {
    day: '2-digit',
    month: 'long',
    year: 'numeric'
  }).replace(' ', ' ').toUpperCase()
}

// 获取新闻标题
function getNewsTitle(index) {
  const titles = [
    'Mu Tianyu, a doctoral student at the School of Economics and Management of the ...',
    'The 2025 Summer Academic Symposium on Financial Economics and Data Science ...',
    'Mu Tianyu, a 2019 doctoral candidate at the School of Economics and Management at ...'
  ]
  return titles[index] || carbonPathList.value[index]?.title || titles[0]
}


</script>
<style scoped>
  /* 轮播容器 - 固定高度 */
  .banner-container {
    width: 100vw;
    height: 600px;
    overflow: hidden;
  }

  .carousel-wrapper {
    width: 100%;
    height: 600px;
  }

  .carousel-track {
    position: relative;
    width: 100%;
    height: 600px;
  }

  .carousel-slide {
    width: 100%;
    opacity: 0;
    transition: opacity 0.5s ease-in-out;
    pointer-events: none;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }

  .carousel-slide.active {
    opacity: 1;
    pointer-events: auto;
    z-index: 2;
  }

  /* 左右布局 - 4:6比例 */
  .slide-content {
    display: flex;
    width: 100%;
    height: 600px;
  }

  /* 左侧文字区域 - 40% */
  .text-section {
    flex: 1;
    background: #2B649C;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding: 100px 0 150px;
    flex-shrink: 0;
    height: 600px;
    position: relative;
  }

  .text-content {
    height: 350px;
    padding: 0 76px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
  }

  /* 响应式文字样式 */
  .subtitle {
    color: white;
    font-weight: 400;
    font-size: 16px;
    color: #FFFFFF;
    margin-bottom: clamp(1rem, 2vw, 1.5rem);
    border-bottom: 1px solid rgba(255,255,255,0.4);
    display: inline-block !important;
    width: fit-content !important;
    max-width: 100%;
  }

  .title {
    color: white;
    font-weight: bold;
    font-size: 48px;
    color: #FFFFFF;
    line-height: 60px;
    height: 300px;
    margin-bottom: 0;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 5;
    line-clamp: 5;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .cta-button {
    background: white;
    color: black;
    font-weight: 500;
    border-radius: 50px;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    width: clamp(180px, 20vw, 244px);
    height: clamp(48px, 6vw, 67px);
    font-size: clamp(0.875rem, 1.2vw, 1rem);
  }

  .cta-button:hover {
    transform: scale(1.05);
  }

  /* 固定轮播序号 - 不参与淡入淡出 */
  .slide-indicators-fixed {
    position: absolute;
    bottom: 50px;
    left: 76px;
    display: flex;
    gap: 1rem;
    z-index: 100;
  }

  .indicator {
    color: white;
    cursor: pointer;
    transition: opacity 0.3s ease;
    font-size: 16px;
    opacity: 0.6;
  }

  .indicator.active {
    opacity: 1;
  }

  /* 右侧图片区域 - 60% */
  .image-section {
    width: 901px;
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    background: #2B649C;
    position: relative;
    height: 600px;
    overflow: hidden;
  }

  /* 图片容器 - 根据左侧文本高度自适应 */
  .image-container {
    width: 901px;
    height: 600px;
    overflow: hidden;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 400px;
  }

  .slide-image {
    width: auto;
    height: 600px;
    object-fit: contain;
    object-position: center;
    display: block;
  }



  .chengshi .grid .text-center:first-child {
    padding-left: 0;
  }
  .chengshi .grid .text-center:last-child {
    padding-right: 0;
  }

  /** 段落标题 */
  .paragraph-healing {
    font-weight: bold;
    font-size: 48px;
    color: #1F2220;
    line-height: 90px;
  }
  .paragraph-subhealing {
    font-weight: 500;
    font-size: 20px;
    color: #2B649C;
    line-height: 20px;
  }
  .content-grid-item {
    background: #FFFFFF;
    box-shadow: 0px 20px 30px 0px rgba(0,0,0,0.08);
    border-radius: 5px 5px 5px 5px;
    cursor: pointer;
  }
  .content-grid-item:hover {
    background: #2B649C;
    box-shadow: 0px 20px 30px 0px rgba(43,100,156,0.3);
    color: #fff;
  }
  .content-grid-item:hover * {
    color: #fff !important;
  }

  /* Selected section 悬浮效果优化 */
  .selected-section .grid {
    overflow: visible;
  }

  .selected-section .grid > * {
    position: relative;
    z-index: 1;
  }

  .selected-section .grid > *:hover {
    z-index: 10;
  }

  /* 移动端响应式优化 */
  @media (max-width: 768px) {
    .slide-content {
      flex-direction: column;
      height: auto;
    }

    .text-section {
      width: 100%;
      height: auto;
      min-height: 300px;
      padding: 60px 40px 80px;
    }

    .image-section {
      width: 100%;
      height: 300px;
      min-height: 300px;
    }

    .slide-indicators-fixed {
      left: 40px;
      bottom: 30px;
    }

    .title {
      font-size: 32px;
      line-height: 40px;
      height: auto;
    }
  }

  @media (max-width: 480px) {
    .text-section {
      padding: 40px 20px 60px;
    }

    .title {
      font-size: 24px;
      line-height: 32px;
    }

    .subtitle {
      font-size: 14px;
    }

    .slide-indicators-fixed {
      left: 20px;
      bottom: 20px;
    }
  }
</style>